<template>  
	<view>
		<uni-list style="margin-top: 40rpx;">  
			<!-- 使用v-for指令遍历friends数组 -->  
			<uni-list-chat  
				v-for="(friend, index) in friends"  
				:key="index"  
				:avatar-circle="true"  
				:avatar="friend.avatar "  
				:title="friend.nickName"  
				:note="friend.sign ? '个性签名:' + friend.sign : '无个性签名'" 
				clickable
				@click="gotoMessage(friend)"
			></uni-list-chat>  
		</uni-list>  
	</view>  
</template>  
  
<script>  
import { hasLogin, logout, getUserid } from '@/store/index.js'
export default {
	methods:{
		gotoMessage(friend) {
			// 获取当前登录用户的 ID
			let currentUserId = this.user.userId;
	
			// 判断传递的用户 ID 是否为当前登录用户的 ID
			let targetUserId = friend.userId1 === currentUserId ? friend.userId2 : friend.userId1;
	
			// 导航到消息页面，并传递目标用户的信息
			uni.navigateTo({
				url: '/pages/version1/friend_page?userId=' 
				            + targetUserId + '&nickName=' + friend.nickName + '&avatar=' + friend.avatar
			})
			console.log("friend: ",friend)
		}
	},
	data() {
		return {
			friends: [],
			user: {
				userId: 0,
				avatar: '',
				nickName: '',
				sign: ''
			},
		};
	},
    onLoad() {
		uni.setNavigationBarTitle({
			title: '好友列表'  
		});
		
		if(hasLogin()) {
			let userInfoStr = uni.getStorageSync("userInfo");
			if (userInfoStr) {
				let userInfo = JSON.parse(userInfoStr);				
				this.user.userId = userInfo.userId || '';
				this.user.nickName = userInfo.nickName || '';
				this.user.avatar = userInfo.avatar || '';
				this.user.sign = userInfo.sign || '';
			}
		}
		
		uni.request({
			url: `http://localhost:8090/api/friends/list/${this.user.userId}`, // 后端提供的好友列表接口地址
			method: 'GET', 
			success: (res) => {
				if (res.data.message) {
					uni.showToast({
						title: '好友列表已获取',
						icon: 'success',
					});
					this.friends = res.data.data;
				} else { 
					uni.showModal({
						title: '提示',
						content: '好友列表获取时遇到问题，请稍后重试！',
					});
				}
			},
			fail: () => {
				uni.showModal({
					title: '网络错误',
					content: '无法连接服务器，请检查网络连接！',
				});
			},
		});
	},
};  
</script>

<style scoped>
	
</style>